package xingkong.tools;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jfinal.plugin.activerecord.Record;

public class MD5Util {
	//16进制下数字到字符的映射数组
	private final static String[] hexDigits = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
	
	private final static String[] numArrays = {"0","1","2","3","4","5","6","7","8","9"};
	
	/**
	 * 将一个字节转化成十六进制形式的字符串
	 * @param b 字节
	 * @return
	 */
	private static String byteToHexString(byte b){
		int n =b;
		if(n<0)n+=256;
		int d1 = n/16;
		int d2 = n%16;
		return hexDigits[d1]+hexDigits[d2];
	}
	
	/**
	 * 将一个字节数组转换成十六进制的字符串
	 * @param b 字节数组
	 * @return 十六进制的字符串
	 */
	private static String byteArrayToHexString(byte[] bytes){
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			sb.append(byteToHexString(bytes[i]));
		}
		return sb.toString();
	}
	
	/**
	 * 对字符串进行MD5编码
	 * @param str
	 * @return
	 */
	private static String encodeByMD5(String str){
		if(null == str || "".equals(str)){
			return null;
		}
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			byte[] bytes = md5.digest(str.getBytes());
			String result = byteArrayToHexString(bytes);
			return result;
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * MD5加密
	 * @param str
	 * @return
	 */
	public static String md5(String str){
		return encodeByMD5(str);
	}
	
	public static List<Record> bankMD5(){
		List<Record> list = new ArrayList<Record>();
		long d = System.currentTimeMillis();
		for (int i = 0; i < numArrays.length; i++) {
			for (int j = 0; j < numArrays.length; j++) {
				for (int j2 = 0; j2 < numArrays.length; j2++) {
					for (int k = 0; k < numArrays.length; k++) {
						for (int k2 = 0; k2 < numArrays.length; k2++) {
							for (int l = 0; l < numArrays.length; l++) {
								StringBuilder sb = new StringBuilder();
								sb.append(numArrays[i])//
									.append(numArrays[j])//
									.append(numArrays[j2])//
									.append(numArrays[k])//
									.append(numArrays[k2])//
									.append(numArrays[l]);
								System.out.println(sb.toString());
								Record record = new Record().set("origin_str", sb.toString()).set("md532_str", MD5Util.md5(sb.toString())).set("create_time", new Date());
								list.add(record);
							}
						}
					}
				}
			}
		}
		long d1 = System.currentTimeMillis();
		System.out.println("第一层循环："+(d1-d));
		return list;
	}
	
	public static void main(String[] args) {
		System.out.println(md5("admin"));
	}
}
